<script setup>
import {onMounted, reactive, ref} from "vue";
import {ElMessage} from 'element-plus';
import http from "@/request/Http.js";
import {Search} from "@element-plus/icons-vue";

// 商品状态映射
const statusMap = {
  0: {text: "下架", type: "info"},
  1: {text: "上架", type: "success"},
  2: {text: "审核中", type: "primary"},
  3: {text: "已售出", type: "warning"},
  4: {text: "已预订", type: "info"},
  5: {text: "审核不通过", type: "danger"}
};

// 审核状态映射
const auditStatusMap = {
  0: {text: "未审核", type: "info"},
  1: {text: "审核通过", type: "success"},
  2: {text: "审核不通过", type: "danger"}
};

// 下架原因选项
const takeDownReasons = [
  {value: '商品信息不实', label: '商品信息不实'},
  {value: '商品违规', label: '商品违规'},
  {value: '卖家违规', label: '卖家违规'},
  {value: '重复商品', label: '重复商品'},
  {value: '其他原因', label: '其他原因'}
];

// 商品列表
const goodList = ref([]);

// 搜索相关
const searchForm = reactive({
  productName: '',
  categoryId: '',
  createTime: '',
  minPrice: '',
  maxPrice: ''
});

// 分类列表
const categoryList = ref([]);

// 分页相关
const currentPage = ref(1);
// 每页条数
const pageSize = ref(10);
// 总记录数
const total = ref(0);

// 详情弹窗相关
const detailDialogVisible = ref(false);
const detailRow = ref({});

// 下架原因弹窗相关
const takeDownDialogVisible = ref(false);
const takeDownForm = ref({
  id: null,
  reason: '',
  selectedReason: '' // 新增下拉选择的原因
});

// 根据分类ID获取分类名称
const getCategoryNameById = (categoryId) => {
  const category = categoryList.value.find(item => item.id === categoryId);
  return category ? category.name : '';
};

// 获取商品列表
const getGoodList = async () => {
  const params = {
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    productName: searchForm.productName,
    categoryId: searchForm.categoryId,
    createdAt: searchForm.createTime,
    minPrice: searchForm.minPrice,
    maxPrice: searchForm.maxPrice
  };

  http.get('/admin/getProductList', {params}).then((response) => {

    // 处理分页信息
    currentPage.value = response.data.current;
    pageSize.value = response.data.size;
    total.value = response.data.total;

    if (response.code === 200) {
      goodList.value = response.data.records;
    } else {
      ElMessage.error(response.message || '获取商品列表失败');
    }
  }).catch((error) => {
    console.error('获取商品列表失败:', error);
    ElMessage.error('获取商品列表失败');
  });
};

// 获取分类列表
const getCategoryList = async () => {
  http.get('/classify/getAllCategories').then((response) => {

    if (response.code === 200) {
      categoryList.value = response.data;
    } else {
      ElMessage.error(response.msg || '获取分类列表失败');
    }
  }).catch((error) => {
    ElMessage.error('获取分类列表失败');
  });
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getGoodList();
};

// 重置搜索
const handleReset = () => {
  searchForm.productName = '';
  searchForm.categoryId = '';
  searchForm.createTime = '';
  currentPage.value = 1;
  getGoodList();
};

// 打开下架原因弹窗
const openTakeDownDialog = (row) => {
  takeDownForm.value.id = row.id;
  takeDownForm.value.reason = '';
  takeDownForm.value.selectedReason = '';
  takeDownDialogVisible.value = true;
};

// 处理下拉选择的下架原因
const handleReasonChange = (value) => {
  takeDownForm.value.selectedReason = value;
  // 如果选择了"其他原因"，清空自定义原因，让用户自行输入
  if (value !== '其他原因') {
    takeDownForm.value.reason = value;
  } else {
    takeDownForm.value.reason = '';
  }
};

// 确认下架商品
const confirmTakeDown = async () => {
  // 如果选择了"其他原因"但没有填写具体原因，则提示
  if (takeDownForm.value.selectedReason === '其他原因' && !takeDownForm.value.reason) {
    ElMessage.warning('请输入具体的下架原因');
    return;
  }

  // 如果没有选择任何原因但也没有填写自定义原因，则提示
  if (!takeDownForm.value.selectedReason && !takeDownForm.value.reason) {
    ElMessage.warning('请选择或输入下架原因');
    return;
  }

  try {
    // 使用选择的原因或自定义原因
    const finalReason = takeDownForm.value.reason || takeDownForm.value.selectedReason;

    // 创建商品对象，更新状态为下架(0)并添加下架原因
    const product = {
      id: takeDownForm.value.id,
      auditRemark: finalReason
    };

    http.put('/admin/unList', product).then((response) => {
      if (response.data.code === 200) {
        ElMessage.success('下架成功');
        takeDownDialogVisible.value = false;
        getGoodList();
      } else {
        ElMessage.error(response.data.message || '下架失败');
      }
    }).catch((error) => {
      console.error('下架商品失败:', error);
      ElMessage.error('下架商品失败');
    });
  } catch (error) {
    ElMessage.error('操作失败');
    console.error(error);
  }
};

// 下架商品（修改为打开弹窗）
const handleTakeDown = async (row) => {
  openTakeDownDialog(row);
};

// 打开详情弹窗
const openDetailDialog = (row) => {
  // 处理商品图片数据
  let images = [];
  if (row.images && Array.isArray(row.images)) {
    images = row.images.filter(img => img && img.imageUrl).map(img => img.imageUrl);
  }

  // 处理商品评论数据
  let reviews = [];
  if (row.reviews && Array.isArray(row.reviews)) {
    reviews = row.reviews.filter(review => review);
  }

  detailRow.value = {
    ...row,
    categoryName: getCategoryNameById(row.categoryId),
    images: images,
    reviews: reviews
  };
  detailDialogVisible.value = true;
};

// 分页相关方法
const handleCurrentChange = (page) => {
  currentPage.value = page;
  getGoodList();
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  getGoodList();
};

// 页面加载时获取数据
onMounted(() => {
  getGoodList();
  getCategoryList();
});
</script>

<template>
  <div class="goods-page">
    <el-card class="box-card">
      <!-- 搜索表单 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" label-width="auto">
          <el-form-item label="商品名称">
            <el-input
                v-model="searchForm.productName"
                clearable
                placeholder="请输入商品名称"
            />
          </el-form-item>
          <el-form-item label="商品类型">
            <el-select
                v-model="searchForm.categoryId"
                clearable
                placeholder="全部类型"
                style="width: 180px"
            >
              <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
                v-model="searchForm.createTime"
                clearable
                format="YYYY-MM-DD"
                placeholder="请选择创建时间"
                style="width: 200px"
                type="date"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="价格区间">
            <el-input
                v-model="searchForm.minPrice"
                placeholder="最低价"
                style="width: 120px"
                type="number"
            />
            <span style="margin: 0 10px">-</span>
            <el-input
                v-model="searchForm.maxPrice"
                placeholder="最高价"
                style="width: 120px"
                type="number"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="handleSearch">
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 商品列表 -->
      <el-table :data="goodList" border style="width: 100%">
        <el-table-column label="序号" width="60">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="商品ID" prop="id" width="80"/>
        <el-table-column label="商品名称" prop="name"/>
        <el-table-column label="商品描述" prop="description" show-overflow-tooltip/>
        <el-table-column label="价格" prop="price" width="100">
          <template #default="scope">
            ￥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="商品类型" prop="categoryName" width="120">
          <template #default="scope">
            {{ getCategoryNameById(scope.row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createdAt" width="180">
          <template #default="scope">
            {{ scope.row.createdAt || '' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="statusMap[scope.row.status]?.type">
              {{ statusMap[scope.row.status]?.text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" prop="auditStatus" width="120">
          <template #default="scope">
            <el-tag :type="auditStatusMap[scope.row.auditStatus]?.type">
              {{ auditStatusMap[scope.row.auditStatus]?.text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="250">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                  size="small"
                  type="primary"
                  @click="openDetailDialog(scope.row)"
              >
                查看详情
              </el-button>
              <el-button
                  v-if="scope.row.status === 1"
                  size="small"
                  type="warning"
                  @click="handleTakeDown(scope.row)"
              >
                下架
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-bar">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30]"
            :total="total"
            background
            layout="sizes,prev, pager, next, jumper, ->, total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 商品详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="商品详情"
        width="600px"
    >
      <el-form class="view-form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称">
              <span>{{ detailRow?.name || '' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格">
              <span>￥{{ detailRow?.price || '' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品类型">
              <span>{{ detailRow?.categoryName || '' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卖家ID">
              <span>{{ detailRow?.sellerId || '' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-tag :type="statusMap[detailRow?.status]?.type">
                {{ statusMap[detailRow?.status]?.text }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核状态">
              <el-tag :type="auditStatusMap[detailRow?.auditStatus]?.type">
                {{ auditStatusMap[detailRow?.auditStatus]?.text }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <span>{{ detailRow?.createdAt || '' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间">
              <span>{{ detailRow?.updatedAt || '' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品描述">
          <span>{{ detailRow?.description || '' }}</span>
        </el-form-item>

        <!-- 商品图片 -->
        <el-form-item v-if="detailRow?.images && detailRow.images.length > 0" label="商品图片">
          <div class="image-preview-container">
            <img
                v-for="(img, index) in detailRow.images"
                :key="index"
                :src="img"
                alt="商品图片"
                class="product-image"
            />
          </div>
        </el-form-item>

        <!-- 商品评论 -->
        <el-form-item v-if="detailRow?.reviews && detailRow.reviews.length > 0" label="商品评论">
          <div class="reviews-container">
            <div
                v-for="(review, index) in detailRow.reviews"
                :key="index"
                class="review-item"
            >
              <div class="review-content">
                <div class="review-header">
                  <span class="review-user">用户ID: {{ review.userId || '未知' }}</span>
                  <el-rate
                      v-model="review.rating"
                      disabled
                      size="small"
                  />
                </div>
                <div class="review-comment">{{ review.comment || '无评论内容' }}</div>
                <div class="review-date">{{ review.createdAt || '' }}</div>
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 审核备注 -->
        <el-form-item v-if="detailRow?.auditRemark" label="审核备注">
          <span>{{ detailRow?.auditRemark || '' }}</span>
        </el-form-item>

        <!-- 下架原因 -->
        <el-form-item v-if="detailRow?.takeDownReason" label="下架原因">
          <span>{{ detailRow?.takeDownReason || '' }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 下架原因弹窗 -->
    <el-dialog
        v-model="takeDownDialogVisible"
        title="下架商品"
        width="500px"
    >
      <el-form label-width="100px">
        <el-form-item label="下架原因">
          <el-select
              v-model="takeDownForm.selectedReason"
              clearable
              placeholder="请选择下架原因"
              @change="handleReasonChange"
          >
            <el-option
                v-for="item in takeDownReasons"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="具体原因">
          <el-input
              v-model="takeDownForm.reason"
              :disabled="takeDownForm.selectedReason && takeDownForm.selectedReason !== '其他原因'"
              :rows="4"
              placeholder="如选择'其他原因'或不选择下拉选项，请在此输入具体原因"
              type="textarea"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="takeDownDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmTakeDown">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.goods-page {
  min-height: 100vh;
  background: #f5f6fa;
  padding: 32px;
}

.box-card {
  max-width: 1400px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.search-bar .el-form-item {
  margin-bottom: 0;
}

.pagination-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.view-form :deep(.el-form-item__label) {
  font-weight: bold;
}

.view-form :deep(.el-form-item__content) {
  color: #333;
}

.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.product-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
}

.reviews-container {
  max-height: 200px;
  overflow-y: auto;
}

.review-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 5px;
}

.review-user {
  font-weight: bold;
  color: #409eff;
}

.review-comment {
  margin-bottom: 5px;
}

.review-date {
  font-size: 12px;
  color: #999;
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  gap: 5px;
  flex-wrap: nowrap;
}

/* 响应式按钮调整 */
.action-buttons :deep(.el-button) {
  padding: 8px 12px;
  font-size: 12px;
}
</style>